<template>
    <!-- 1 ytq添加商品 -->
    <div class="addProduct">
        <div class="form-container">
            <el-card body-style="padding-bottom:35px">
                <!-- 内容 -->
                <div class="el-card__body">
                    <!-- 步骤条 -->
                    <div class="step">
                        <el-steps align-center :active="active" finish-status="success">
                            <el-step title="填写商品信息" />
                            <el-step title="填写商品促销" />
                            <el-step title="填写商品属性" />
                            <el-step title="选择商品关联" />
                        </el-steps>
                    </div>

                    <!-- 表单form -->
                    <!--  -->
                    <div class="form" style="margin-top: 50px">
                        <!-- 步骤1 -->
                        <el-form v-show="current === 1" :rules="rules" ref="ruleFormRef" :model="ruleForm"
                            label-width="120px">
                            <!-- 1 -->
                            <el-form-item prop="productCategoryId" label="商品分类:">
                                <el-cascader placeholder="请选择" :options="options1" v-model="ruleForm.productCategoryId" />
                            </el-form-item>
                            <!-- 2 -->
                            <el-form-item label="商品名称:" prop="name">
                                <el-input v-model="ruleForm.name" />
                            </el-form-item>
                            <!-- 3 -->
                            <el-form-item label="副标题:" prop="subTitle">
                                <el-input v-model="ruleForm.subTitle" />
                            </el-form-item>
                            <!-- 4 -->
                            <el-form-item label="商品品牌:" prop="brandName">
                                <el-select v-model="ruleForm.brandName" placeholder="请选择品牌">
                                    <el-option v-for="item in optionsA1" :key="item.id" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <!-- 5 -->
                            <el-form-item label="商品介绍:">
                                <el-input v-model="ruleForm.desc" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                            <el-form-item label="商品货号:">
                                <el-input v-model="ruleForm.num" />
                            </el-form-item>
                            <el-form-item label="商品售价:">
                                <el-input v-model="ruleForm.price" />
                            </el-form-item>
                            <el-form-item label="市场价:">
                                <el-input v-model="ruleForm.rmb" />
                            </el-form-item>
                            <el-form-item label="商品库存:">
                                <el-input v-model="ruleForm.stock" />
                            </el-form-item>
                            <el-form-item label="计量单位:">
                                <el-input v-model="ruleForm.unit" />
                            </el-form-item>
                            <el-form-item label="商品重量:">
                                <el-input class="weight" v-model="ruleForm.weight" />&nbsp;&nbsp;&nbsp;克
                            </el-form-item>
                            <el-form-item label="排序:">
                                <el-input v-model="ruleForm.sort" />
                            </el-form-item>
                            <!-- 下一步 -->
                            <el-button class="next_btn_one" type="primary" style="margin-top: 12px"
                                @click="next(ruleFormRef)">下一步，填写商品促销
                            </el-button>
                        </el-form>
                        <!-- 步骤2 -->
                        <el-form v-show="current === 2" label-width="120px">
                            <!-- 1 -->
                            <el-form-item label="赠送积分:">
                                <el-input v-model="ruleForm.integral" />
                            </el-form-item>
                            <!-- 2 -->
                            <el-form-item label="赠送成长值:">
                                <el-input v-model="ruleForm.value" />
                            </el-form-item>
                            <!-- 3 -->
                            <el-form-item label="积分购买限制:">
                                <el-input v-model="ruleForm.limits" />
                            </el-form-item>
                            <!-- 4 -->
                            <el-form-item label="预告商品:">
                                <el-switch v-model="ruleForm.foreshow" />
                            </el-form-item>
                            <!-- 5 -->
                            <el-form-item label="商品上架:">
                                <el-switch v-model="ruleForm.sale" />
                            </el-form-item>
                            <el-form-item label="商品推荐:">
                                <el-switch inactive-text="新品" v-model="ruleForm.new" />&nbsp;&nbsp;&nbsp;
                                <el-switch inactive-text="推荐" v-model="ruleForm.recommend" />
                            </el-form-item>
                            <el-form-item label="服务保证:" prop="promise">
                                <el-checkbox v-model="ruleForm.return">无忧退货</el-checkbox>
                                <el-checkbox v-model="ruleForm.fast">快速退款</el-checkbox>
                                <el-checkbox v-model="ruleForm.free">免费包邮</el-checkbox>
                            </el-form-item>
                            <el-form-item label="详细页标题:">
                                <el-input v-model="ruleForm.detailTitle" />
                            </el-form-item>
                            <el-form-item label="详细页描述:">
                                <el-input v-model="ruleForm.detailDesc" />
                            </el-form-item>
                            <el-form-item label="商品关键字:">
                                <el-input v-model="ruleForm.keyword" />
                            </el-form-item>
                            <el-form-item label="商品备注:">
                                <el-input type="textarea" v-model="ruleForm.notes" />
                            </el-form-item>
                            <el-form-item label="选择优惠方式:">
                                <div class="demo-button-style">
                                    <el-checkbox-group v-model="checkboxGroup4" size="small">
                                        <el-checkbox-button v-for="discountWay in discountWays" :key="discountWay"
                                            :label="discountWay">{{ discountWay }}</el-checkbox-button>
                                    </el-checkbox-group>
                                </div>
                            </el-form-item>
                            <!-- 下一步 -->
                            <el-button class="next_btn_one next_btn_two" style="margin-top: 12px"
                                @click="last(ruleFormRef)">上一步，填写商品信息
                            </el-button>
                            <el-button class="next_btn_one next_btn_two" type="primary" style="margin-top: 12px"
                                @click="next(ruleFormRef)">下一步，填写商品属性
                            </el-button>
                        </el-form>
                        <!-- 步骤3 -->
                        <el-form v-show="current === 3" label-width="120px">
                            <!-- 1 -->
                            <el-form-item label="属性类型:">
                                <el-select v-model="ruleForm.brand" placeholder="请选择属性类型">
                                    <el-option v-for="item in optionsB1" :key="item.id" :label="item.value"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <!-- 2 -->
                            <el-form-item label="商品规格:">
                                <div class="gray"></div>
                                <el-table border style="width: 100%; margin-top: 20px; margin-bottom: 20px">
                                    <el-table-column label="销售价格" />
                                    <el-table-column label="商品库存" />
                                    <el-table-column label="库存预警值" />
                                    <el-table-column label="SKU编号" />
                                    <el-table-column label="操作" />
                                </el-table>
                                <el-button type="primary" @click="refresh">
                                    刷新列表
                                </el-button>
                                <el-button type="primary" @click="syncPrice">
                                    同步价格
                                </el-button>
                                <el-button type="primary" @click="syncStock">
                                    同步库存
                                </el-button>
                            </el-form-item>
                            <!-- 3 -->
                            <el-form-item label="商品参数:">
                                <div class="gray"></div>
                            </el-form-item>
                            <!-- 4 -->
                            <el-form-item label="商品相册:">
                                <el-upload class="avatar-uploader"
                                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                    :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload" v-model="ruleForm.albumPics">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                            <!-- 5 -->
                            <el-form-item label="规格参数:">
                                <el-tabs type="border-card">
                                    <el-tab-pane label="电脑端详情"></el-tab-pane>
                                    <el-tab-pane label="移动端详情"></el-tab-pane>
                                    <!-- 富文本 -->
                                    <vue-quill-text-editor ref="quillRef" />
                                </el-tabs>
                            </el-form-item>
                            <!-- 下一步 -->
                            <el-button class="next_btn_one next_btn_two" style="margin-top: 12px"
                                @click="last(ruleFormRef)">上一步，填写商品促销
                            </el-button>
                            <el-button class="next_btn_one next_btn_two" type="primary" style="margin-top: 12px"
                                @click="next(ruleFormRef)">下一步，选择商品关联
                            </el-button>
                        </el-form>
                        <!-- 步骤4 -->
                        <el-form v-show="current === 4" label-width="120px">
                            <p style="text-align: center; margin: 0 0 20px"></p>
                            <div style="text-align: center">
                                <!-- 1 -->
                                <el-form-item label="关联专题:">
                                    <el-transfer v-model="rightValue" style="text-align: left; display: inline-block"
                                        filterable filter-placeholder="请输入专题名称" :left-default-checked="['']"
                                        :right-default-checked="[]" :titles="['待选择', '已选择']" :button-texts="['', '']"
                                        :format="{
                                            noChecked: '${total}',
                                            hasChecked: '${checked}/${total}',
                                        }" :data="data1">
                                    </el-transfer>
                                </el-form-item>
                                <!-- 2 -->
                                <p style="text-align: center; margin: 50px 0 20px"></p>
                                <el-form-item label="关联优选:">
                                    <div style="text-align: center">
                                        <el-transfer v-model="leftValue" style="text-align: left; display: inline-block"
                                            filter-placeholder="请输入优选名称" filterable :left-default-checked="[]"
                                            :right-default-checked="[]" :titles="['待选择', '已选择']" :button-texts="['', '']"
                                            :format="{
                                                noChecked: '${total}',
                                                hasChecked: '${checked}/${total}',
                                            }" :data="data2">
                                            <template #default="{ option }">
                                                <span>{{ option.label }}</span>
                                            </template>
                                        </el-transfer>
                                    </div>
                                </el-form-item>
                            </div>
                            <el-button class="next_btn_one next_btn_two" style="margin-top: 12px"
                                @click="last(ruleFormRef)">上一步，填写商品属性
                            </el-button>
                            <el-button class="next_btn_one next_btn_two" type="primary" style="margin-top: 12px"
                                @click="submit(ruleFormRef)">完成，提交商品
                            </el-button>
                        </el-form>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script lang="ts" setup>
import {
    ref,
    reactive,
    watch,
    onBeforeUnmount,
    shallowRef,
    onMounted,
} from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import type { IBrandListItem } from '../../request/addProduct'
import * as api from "../../request/api";
import router from "../../router";

let msg = ref('添加商品')
let txt = ref('商品')
let path1 = ref('pms/addProduct')
let aaa = ref(0)


const ruleFormRef = ref<FormInstance>();

// 当前步骤
let current = ref(1);

// 校验每一项
const ruleForm = reactive({
    albumPics: "",
    brandId: '',
    brandName: "",
    deleteStatus: 0,
    description: "",
    detailDesc: "",
    detailHtml: "",
    detailMobileHtml: "",
    detailTitle: "",
    feightTemplateId: 0,
    flashPromotionCount: 0,
    flashPromotionId: 0,
    flashPromotionPrice: 0,
    flashPromotionSort: 0,
    giftPoint: 0,
    giftGrowth: 0,
    keywords: "",
    lowStock: 0,
    name: "",
    newStatus: 0,
    note: "",
    originalPrice: 0,
    pic: "",
    memberPriceList: [
        {
            memberLevelId: 1,
            memberLevelName: "黄金会员",
        },
        {
            memberLevelId: 2,
            memberLevelName: "白金会员",
        },
        {
            memberLevelId: 3,
            memberLevelName: "钻石会员",
        },
    ],
    productFullReductionList: [
        {
            fullPrice: 0,
            reducePrice: 0,
        },
    ],
    productLadderList: [
        {
            count: 0,
            discount: 0,
            price: 0,
        },
    ],
    previewStatus: 0,
    price: '',
    productAttributeCategoryId: null,
    productAttributeValueList: [],
    skuStockList: [],
    subjectProductRelationList: [],
    prefrenceAreaProductRelationList: [],
    productCategoryId: '',
    productCategoryName: "11111",
    productSn: "",
    promotionEndTime: "",
    promotionPerLimit: 0,
    promotionPrice: null,
    promotionStartTime: "",
    promotionType: 0,
    publishStatus: 0,
    recommandStatus: 0,
    sale: 0,
    serviceIds: "",
    sort: '',
    stock: '',
    subTitle: "",
    unit: "",
    usePointLimit: 0,
    verifyStatus: 0,
    weight: '',
});
const rules = reactive<FormRules>({
    //商品分类
    productCategoryId: [
        {
            required: true,
            message: "请选择商品分类",
            trigger: "change",
        },
    ],
    //商品名称
    name: [
        { required: true, message: "请输入商品名称", trigger: "blur" },
        { min: 2, max: 140, message: "长度在 2 到 140 个字符", trigger: "blur" },
    ],
    //副标题
    subTitle: [{ required: true, message: "请输入商品副标题", trigger: "blur" }],
    //商品品牌
    brandName: [{ required: true, message: "请选择商品品牌", trigger: "change" }],
});

// 上一步，下一步
const active = ref(0);
const last = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (active.value-- === 0) active.value < 4;
            current.value = active.value + 1;
            // console.log('last,active.value', active.value)
        } else {
            console.log("error submit!", fields);
        }
    });
};
const next = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (active.value++ > 3) active.value = 0;
            current.value = active.value + 1;
            // console.log('next,active.value', active.value)
        } else {
            console.log("error submit!", fields);
        }
    });
};


let options1 = ref([])
// 步骤1.1 商品分类请求 
// let options2 = []; //??渲染options1
let productCategoryFn = async () => {
    let productCategoryRes2: any = await api.addProduct.productCategory();
    // options1 = productCategoryRes2 //×
    let options2 = productCategoryRes2.map((item: any) => {
        let children = item.children.map((item2: any) => {
            return {
                value: item2.name,
                label: item2.name,
            }
        })
        return {//格式处理
            value: item.name,
            label: item.name,
            children
        }
    })
    options1.value = options2
};
productCategoryFn();
// 步骤1.2 商品品牌请求   
let optionsA1 = ref([])
let brandListFn = async () => {
    let brandListRes2: any = await api.addProduct.brandList({
        pageNum: 1,
        pageSize: 100,
    });
    // brandlist = brandListRes2.list;//×
    let optionsA2 = brandListRes2.list.map((item: any) => {
        // console.log('item', item)
        return {//格式处理
            value: item.name,
        }
    })
    optionsA1.value = optionsA2

};
brandListFn();

// 步骤2 选择优惠方式
const checkboxGroup4 = ref(["无优惠"]);
const discountWays = ["无优惠", "特惠促销", "会员价格", "阶梯价格", "满减价格"];

// 步骤3 属性类型请求
// let brandlist = [];
// let attrCategoryList = [];
let optionsB1 = ref([])
let attrCategoryFn = async () => {
    let attrCategoryRes2: any = await api.addProduct.attrCategory({
        pageNum: 1,
        pageSize: 100,
    });
    // brandlist = attrCategoryRes2.list; //×
    let optionsB2 = attrCategoryRes2.list.map((item: any) => {
        return {//格式处理
            value: item.name,
        }
    })
    optionsB1.value = optionsB2
};
attrCategoryFn();
// 步骤3 商品规格三个按钮
let refresh = () => {
    ElMessageBox.confirm("刷新列表将导致sku信息重新生成，是否要刷新", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            ElMessage({
                type: "success",
                message: "刷新成功",
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消刷新",
            });
        });
};
let syncPrice = () => {
    ElMessageBox.confirm("将同步第一个sku的价格到所有sku，是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            ElMessage({
                type: "success",
                message: "确定同步价格",
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消同步价格",
            });
        });
};
let syncStock = () => {
    ElMessageBox.confirm("将同步第一个sku的库存到所有sku，是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            ElMessage({
                type: "success",
                message: "确定同步库存",
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消同步库存",
            });
        });
};
// 步骤3 商品相册
const imageUrl = ref("");
const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.type !== "image/jpeg") {
        ElMessage.error("照片必须是jpg格式");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("照片大小不能超过2MB");
        return false;
    }
    return true;
};
//步骤3 富文本
const quillRef = ref();

interface Option {
    key: number;
    label: string;
    initial: string;
}
//步骤4 选择商品关联
//??format页数无法调出
const generateData1 = (): Option[] => {
    const data1: Option[] = [];
    // let subjectListRes2 = await api.addProduct.subjectList()
    // console.log('subjectListRes2', subjectListRes2)
    // const states1 = [...subjectListRes2.title]

    const states1 = [
        "polo衬衫的也时尚",
        "大牌手机低价秒",
        "晓龙845新品上市",
        "夏天应该穿什么",
        "夏季精选",
        "品牌手机降价",
    ];
    const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
    states1.forEach((city, index) => {
        data1.push({
            label: city,
            key: index,
            initial: initials[index],
        });
    });
    return data1;
};
const generateData2 = (): Option[] => {
    const data2: Option[] = [];
    const states2 = [
        "让音质更出众",
        "让音质更出众22",
        "让音质更出众33",
        "让音质更出众44",
    ];
    const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
    states2.forEach((city, index) => {
        data2.push({
            label: city,
            key: index,
            initial: initials[index],
        });
    });
    return data2;
};
const data1 = ref(generateData1());
const data2 = ref(generateData2());
const rightValue = ref([]);
const leftValue = ref([]);
const handleChange = (
    value: number | string,
    direction: "left" | "right",
    movedKeys: string[] | number[]
) => {
    console.log(value, direction, movedKeys);
};
//步骤4 列表请求
// let subjectListFn = async () => {
//     let subjectListRes2 = await api.addProduct.subjectList()
//     console.log('subjectListRes2', subjectListRes2)
// }
let preferListFn = async () => {
    let preferListRes2 = await api.addProduct.preferList();
    // console.log('preferListRes2', preferListRes2)
};
preferListFn();




// 提交添加

const submit = async (formEl: FormInstance | undefined,) => {
    // row = ruleForm;
    // row: IBrandListItem
    // console.log(row)
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            ElMessageBox.confirm("是否提交数据? ", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                //添加
                let row2 = {
                    brandId: Number(ruleForm.brandId),
                    productCategoryId: Number(ruleForm.productCategoryId),
                    sort: Number(ruleForm.sort),
                    weight: Number(ruleForm.weight),
                    stock: Number(ruleForm.stock),
                    price: Number(ruleForm.price),
                    // name: "",
                    name: ruleForm.name,
                    albumPics: "",
                    brandName: ruleForm.brandName,
                    deleteStatus: 0,
                    description: "",
                    detailDesc: "",
                    detailHtml: "",
                    detailMobileHtml: "",
                    detailTitle: "",
                    feightTemplateId: 0,
                    flashPromotionCount: 0,
                    flashPromotionId: 0,
                    flashPromotionPrice: 0,
                    flashPromotionSort: 0,
                    giftPoint: 0,
                    giftGrowth: 0,
                    keywords: "",
                    lowStock: 0,
                    newStatus: 0,
                    note: "",
                    originalPrice: 0,
                    pic: "",
                    memberPriceList: [
                        {
                            memberLevelId: 1,
                            memberLevelName: "黄金会员",
                        },
                        {
                            memberLevelId: 2,
                            memberLevelName: "白金会员",
                        },
                        {
                            memberLevelId: 3,
                            memberLevelName: "钻石会员",
                        },
                    ],
                    productFullReductionList: [
                        {
                            fullPrice: 0,
                            reducePrice: 0,
                        },
                    ],
                    productLadderList: [
                        {
                            count: 0,
                            discount: 0,
                            price: 0,
                        },
                    ],
                    previewStatus: 0,
                    // price: 0,
                    productAttributeCategoryId: null,
                    productAttributeValueList: [],
                    skuStockList: [],
                    subjectProductRelationList: [],
                    prefrenceAreaProductRelationList: [],
                    // productCategoryId: 197,
                    productCategoryName: "11111",
                    productSn: "",
                    promotionEndTime: "",
                    promotionPerLimit: 0,
                    promotionPrice: null,
                    promotionStartTime: "",
                    promotionType: 0,
                    publishStatus: 0,
                    recommandStatus: 0,
                    sale: 0,
                    serviceIds: "",
                    // sort: 0,
                    // stock: 0,
                    subTitle: "",
                    unit: "",
                    usePointLimit: 0,
                    verifyStatus: 0,
                    // weight: 0,
                }
                let productCreateData = await api.addProduct.productCreate(row2)
                console.log(productCreateData)
                // tableData[createData].push(createData)
                ElMessage({
                    type: "success",
                    message: "提交成功",
                });
                router.go(0)
            })
                .catch(() => {
                    ElMessage({
                        type: "info",
                        message: "取消提交",
                    });
                });

        } else {
            ElMessage({
                type: "error",
                message: "验证失败",
            });
        }
    });
};

</script>

<style lang="scss" scoped>
:deep .el-table thead {
    font-weight: 700;
}

:deep .el-switch__label.is-active {
    color: black;
}

.el-input,
.el-textarea {
    width: 450px;
}

.weight {
    width: 250px;
}

.addProduct {
    background-color: white;
}

.breadcrumb {
    height: 45px;
    border-bottom: 1px solid #ebeef5;
    font-size: 20px;
}

:deep .el-table .el-table__cell {
    text-align: center !important;
}

.el-card__body {
    padding: 40px !important;
}

.el-card.is-always-shadow {
    box-shadow: none;
}

.gray {
    width: 100%;
    background-color: #f8f9fc;
    height: 35px;
    border: 1px solid #ebeef5;
}

.next_btn_one {
    position: relative;
    /* width: 100%; */
    left: 50%;
    transform: translateX(-50%);
}

.next_btn_two {
    left: 40%;
}

.form-container {
    left: 0;
    right: 0;
    width: 720px;
    padding: 27px 35px 15px 35px;
    margin: 20px auto;
    width: 850px;
}

.el-card {
    border-radius: 4px;
    /* border: 1px solid #ebeef5; */
    border: 1px solid#ebeef5;
    background-color: #fff;
    overflow: hidden;
    color: #303133;
    transition: 0.3s;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

:deep .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

:deep .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>